var bundle = {
	"action" : "",
	"type" : "server",
	"content" : ""
};
var ws = null;
$(function(){
    //连接服务器
    ws = new WebSocket("ws://"+window.location.hostname+":8003");
    //连接成功触发
    ws.onopen = function(){
        alert("连接成功");
        bundle.action = "connect";
        fire(bundle);
    }
    //连接失败触发
    ws.onerror = function(){
        alert("连接失败");
    }

    ws.onmessage = function(msg){
        console.log(msg.data);
        if(msg.data == ""){
            return;
        }
        var action = JSON.parse(msg.data);

        switch (action.type) {
            case "setGroup":
            createGroup(action.data);
                break;
            default:
                // statements_def
                break;
        }
    }
})


function fire(bundle){
    bundle.type = "server";
    ws.send(JSON.stringify(bundle));
}
function createGroup(arr) {
    var html = "";
    for(var i=0;i<arr.length;i++){
        html += '<div class="item"><div class="input-group"><input type="text" class="form-control" id="int'+(i+1)+'" placeholder="'+arr[i]+'">';
        html += '<span class="input-group-btn">';
        html += '<button class="btn btn-primary" type="button" onclick="add('+(i+1)+');">加分</button>';
        html += '</span></div></div>'
    }

    $("#box").html(html);
}

function add(type) {
    var str = type+"|"+$("#int"+type).val();
    $("#int"+type).val("");
    var action = {
        type:"addSecond",
        data:str
    }
    bundle.action = "chat";
    bundle.content = action;
    fire(bundle);
    
}



